<template>
  <div id="LoginIndex">
    <!-- 登录框体 -->
    <div class="LoginDiv">
      <el-row>
        <el-col :span="8">
          <div class="loginBanner">123</div>
        </el-col>
        <el-col :span="16">
          <div class="loginContext">
            <div class="formDiv">
              <!-- 登录表单
                            ref：dom节点名称
                            model: 表单数据对象
                            label-width: 表单描述文字的宽度
                        -->
              <el-form
                ref="loginForm"
                :rules="loginRule"
                :model="loginData"
                label-width="80px"
              >
                <el-form-item style="text-align: center;">
                  <h2>登录</h2>
                </el-form-item>
                <el-form-item prop="userName">
                  <el-input
                    v-model="loginData.userName"
                    autocomplete="off"
                    placeholder="用户名"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="pwd">
                  <el-input
                    type="password"
                    autocomplete="off"
                    :show-password="true"
                    v-model="loginData.pwd"
                    placeholder="密码"
                  ></el-input>
                </el-form-item>
                <el-form-item prop="reqCode">
                  <el-row>
                    <el-col :span="18">
                      <el-input
                        v-model="loginData.reqCode"
                        placeholder="验证码"
                      ></el-input>
                    </el-col>
                    <el-col :span="6">
                      <img
                        @click="getReqCode"
                        class="reqCodeImg"
                        :src="imgSrc"
                      />
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item>
                  <el-checkbox v-model="loginData.isRe"
                    >是否记住当前账号</el-checkbox
                  >
                </el-form-item>
                <el-form-item>
                  <el-button
                    :loading="isLoading"
                    style="width: 100%;"
                    type="primary"
                    @click="isUseWxyzm"
                    >登录</el-button
                  >
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-col>
      </el-row>
    </div>

    <!-- 系统名称 -->
    <h1 class="sysNameTitle">{{ sysName }}</h1>
    <!-- 版权信息 -->
    <div class="copyDiv" v-html="copyHtml"></div>

    <!-- 行为验证码 -->
    <div class="xwDiv" v-if="isVerify">
      <Verify
        @success="verifySuccess"
        mode="pop"
        captchaType="blockPuzzle"
        :imgSize="{ width: '330px', height: '155px' }"
        ref="verify"
      ></Verify>
    </div>

  </div>
</template>

<script>
// 引入行为验证码组件
import Verify from "@/components/verifition/Verify";
import * as accountAPI from "@/api/account.js";
import * as reqCodeAPI from "@/api/reqCode.js";

export default {
  name: "LoginIndex",
  components: { Verify }, // 注册行为验证码组件
  data() {
    return {
      isVerify: false,
      // 本机id
      localID: this.$myUtil.getLocalID(),
      //加载
      isLoading: false,
      //系统名称
      sysName: "超级无敌智慧物流管理系统",
      //版权信息
      copyHtml:
        "<span>&copy;高靖博个人所有,未经许可禁止商用或截取,需要可以练习760662328@qq.com</span><br/>" +
        "Copyright © 2021  gdones.com 滇ICP备14013441号-5",
      //登录表单数据
      loginData: {
        userName: $cookies.get("userName"),
        pwd: null,
        reqCode: null,
        isRe: false,
        isChecked: false
      },
      imgSrc: null,
      // 表单验证规则
      loginRule: {
        //用户名必填
        userName: { required: true, message: "请输入用户名", trigger: "blur" }, //blur 输入之后触发校验
        pwd: { required: true, message: "请输入密码", trigger: "blur" },
        reqCode: { required: true, message: "请输入验证码", trigger: "blur" }
      }
    };
  },
  mounted() {
    //请求验证码
    this.getReqCode();

  },
  methods: {
    // 行为验证码回调成功
    verifySuccess(data) {
      console.dir("行为验证码验证成功！");
      console.dir(data); // 是返回了一个可以传递到后端进行二次验证操作的对象

      this.isVerify = false;

      // 添加参数
      this.loginData.isChecked = true; // 告诉后端行为验证已完成

      // 可以调用登录操作
      this.doLogin();
    },
    // 判断是否需要行为验证码
    isUseWxyzm() {
      this.isLoading = true;
      let _this = this;
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          accountAPI
            .checkIsUseXwyz({
              ..._this.loginData,
              localID: _this.localID
            })
            .then(function(res) {
              if (res.code == "-4") {
                // 需要开启行为验证

                // 需要打开行为验证码
                _this.isVerify = true;
              } else if (res.code == "0000") {
                //保存token---保存到localstorage
                window.localStorage.setItem("token", res.data.token);

                delete res.data.user.acpwd; // 删除密码字段

                window.localStorage.setItem(
                  "dsadasdasd1223213dsa32145r32",
                  JSON.stringify(res.data.user)
                );

                if (_this.loginData.isRe == true) {
                  // 需要记住账号
                  _this.$cookies.set("userName", _this.loginData.userName); // 不设置时间，默认1天过期
                }

                _this.getAllSysUserData(res.data.user.accountID); // 获取用户的所有信息

                //登录成功
                //this.$message.success('错了哦，这是一条错误消息');
                _this.$message({
                  showClose: true,
                  message: "登录成功，正在跳转...",
                  type: "success",
                  onClose: function() {
                    _this.$router.push("/main");
                    _this.isLoading = false;
                  }
                });
              } else if (res.code == "-2") {
                _this.getReqCode();
                _this.isLoading = false;
              } else {
                _this.isLoading = false;
              }
            });
        } else {
          this.isLoading = false;
          return false; // 阻止冒泡事件，阻止原生表单提交功能
        }
      });
    },
    //登录功能
    doLogin() {
      this.isLoading = true;
      this.$refs.loginForm.validate(valid => {
        // valid 验证是否通过：true通过 false没通过
        if (valid) {
          // 调用axios
          let _this = this;
          accountAPI
            .doLogin({
              ..._this.loginData,
              localID: _this.localID
            })
            .then(function(res) {
              if (res.code == "0000") {
                //保存token---保存到localstorage
                window.localStorage.setItem("token", res.data.token);

                delete res.data.user.acpwd; // 删除密码字段

                window.localStorage.setItem(
                  "dsadasdasd1223213dsa32145r32",
                  JSON.stringify(res.data.user)
                );

                if (_this.loginData.isRe == true) {
                  // 需要记住账号
                  _this.$cookies.set("userName", _this.loginData.userName); // 不设置时间，默认1天过期
                }

                _this.getAllSysUserData(res.data.user.accountID); // 获取用户的所有信息

                //登录成功
                //this.$message.success('错了哦，这是一条错误消息');
                _this.$message({
                  showClose: true,
                  message: "登录成功，正在跳转...",
                  type: "success",
                  onClose: function() {
                    _this.$router.push("/main");
                    _this.isLoading = false;
                  }
                });
              } else if (res.code == "-2") {
                _this.getReqCode();
                _this.isLoading = false;
              } else {
                _this.isLoading = false;
              }
            })
            .catch(function(err) {
              console.dir(err);
            });
        } else {
          this.isLoading = false;
          return false; // 阻止冒泡事件，阻止原生表单提交功能
        }
      });
    },
    //获取验证码的方法
    getReqCode() {
      let _this = this;
      reqCodeAPI.captcha(_this.localID).then(function(res) {
        if (res.code == "0000") {
          _this.imgSrc = res.data;
        }
      });
    },
    //获取用户所有信息的方法
    getAllSysUserData(accountID) {
      let _this = this;
      accountAPI.getAllSysData(accountID).then(function(response) {
        if (response.code == "0000") {
          if (response.data.roleMenu) {
            // 角色关联菜单数据转换
            let treeData = _this.$myUtil.list2TreeData(
              response.data.roleMenu,
              "-1",
              "menuID"
            );
            response.data.menuTreeData = treeData;
          }
          window.localStorage.setItem("user", JSON.stringify(response.data));
        }
      });
    }
  }
};
</script>

<!-- CSS代码 -->
<style scoped>
#LoginIndex {
  background-image: url("../assets/bk.jpg");
  width: 100vw;
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-repeat: no-repeat;
}
.LoginDiv {
  width: 850px;
  height: 650px;
  background-color: #fff;
  border-radius: 7px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}
.loginBanner {
  width: 100%;
  height: 100%;
}
.loginContext {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
}
.formDiv {
  width: 80%;
  height: 100%;
  display: flex;
  justify-content: center;
  box-sizing: border-box;
  padding-top: 10%;
}
.formDiv > h2 {
  letter-spacing: 10px;
}
.reqCodeImg {
  width: 100%;
}
.sysNameTitle {
  letter-spacing: 2px;
  position: fixed;
  line-height: 10px;
  top: 0;
  left: 10px;
  color: #606266;
}
.copyDiv {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  height: auto;
  text-align: center;
  font-size: 12px;
  color: #909399;
}
</style>
